package com.zhixiang.core.util;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;

/**
 * 通过freemark模板生成符合echart的json格式字符串
 * @author whw
 * @version v1.0
 * @date 2016/6/7
 */
public class EChartUtils {
    public static String getChart(Object rootMap,String ftlName) {
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");

//            String ftlBaseUrl = EChartUtils.class.getResource("/").getPath() + "ftl/chart/";
            String ftlBaseUrl = Utils.getWebinfPath() + "ftl/chart/";

            configuration.setDirectoryForTemplateLoading(new File(ftlBaseUrl));
            Template template = configuration.getTemplate(ftlName + ".ftl", "utf-8");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();// 向OutPutStream中写入，如 message.writeTo(baos);
            Writer writer = new BufferedWriter(new OutputStreamWriter(baos, "utf-8"), 10240);

            template.process(rootMap, writer);
            byte[] lens = baos.toByteArray();
            String content = new String(lens, "utf-8");
            return content;
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
